package com.guangaiboen.attendance.core.util;

import com.google.common.base.Throwables;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import sun.net.util.IPAddressUtil;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * Created by Adam on 2017/12/15.
 */
public class IPUtils extends IPAddressUtil {

    private static final Log log = LogFactory.getLog(IPUtils.class);
    /**
     * 获取本机ip地址，并自动区分Windows还是linux操作系统
     */
    public static String getIpAddress() {
        String sIP;
        InetAddress ip = null;
        try {
            // Windows系统
            if (isWindowsOS()) {
                ip = InetAddress.getLocalHost();
            }
            // 非Windows系统
            else {
                boolean bFindIP = false;
                Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
                while (netInterfaces.hasMoreElements()) {
                    if (bFindIP) {
                        break;
                    }
                    NetworkInterface ni = netInterfaces.nextElement();
                    //if(ni.getName()) { xxx 特定情况，可以考虑用ni.getName判断 }
                    // 遍历所有ip
                    Enumeration<InetAddress> ips = ni.getInetAddresses();
                    while (ips.hasMoreElements()) {
                        ip = ips.nextElement();
                        if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() // 127.开头的都是 Loopback 地址
                                && !ip.getHostAddress().contains(":")) {
                            bFindIP = true;
                            break;
                        }
                    }
                }
            }
        } catch (IOException e) {
            Throwables.throwIfUnchecked(e);
        }
        sIP = null != ip ? ip.getHostAddress() : "unknown";
        log.debug("检索到的当前主机ip地址为：" + sIP);
        return sIP;
    }

    /**
     * 判定是否是 windows 系统
     */
    private static boolean isWindowsOS() {
        return System.getProperty("os.name").toLowerCase().contains("windows");
    }
}
